package com.pureut.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDept;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.domain.SupplierAccess;
import com.pureut.system.domain.SupplierList;
import com.pureut.system.domain.dto.SupplierAccessDeailsDto;
import com.pureut.system.domain.dto.SupplierAccessInitDto;
import com.pureut.system.domain.dto.SupplierAccessPageListDto;
import com.pureut.system.domain.vo.SupplierAccessVo;
import com.pureut.system.domain.vo.SupplierListVo;
import com.pureut.system.export.SupplierAccessExport;
import com.pureut.system.export.SupplierExport;
import com.pureut.system.mapper.SupplierAccessMapper;
import com.pureut.system.mapper.SysDeptMapper;
import com.pureut.system.mapper.SysUserMapper;
import com.pureut.system.service.ISupplierAccessService;
import com.pureut.system.service.ISupplierListService;
import com.pureut.system.service.ISysDeptService;
import com.pureut.system.service.ISysUserService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: pureut
 * @Date: 2024-12-05 17:16:19
 * @Desc: 供应商准入
 */
@Service("supplierAccessService")
public class SupplierAccessServiceImpl extends ServiceImpl<SupplierAccessMapper, SupplierAccess> implements ISupplierAccessService {

    /**
     * 供应商准入Dao
     */
    @Resource
    private SupplierAccessMapper supplierAccessMapper;

    @Resource
    ISysDeptService sysDeptService;
    @Resource
    ISysUserService sysUserService;

    //部门
    @Resource
    SysDeptMapper sysDeptMapper;

    //人员
    @Resource
    SysUserMapper sysUserMapper;

    /**
     * 供应商名录Service
     */
    @Autowired
    private ISupplierListService supplierListService;

    /**
     * 查询列表
     * @param supplierAccessVo
     * @return
     */
    @Override
    public List<SupplierAccessPageListDto> queryPage(SupplierAccessVo supplierAccessVo) {
        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierAccessPageListDto> supplierAccessPageListDtos = supplierAccessMapper.selectByPage(supplierAccessVo);
        supplierAccessPageListDtos.forEach(e->{
            e.setSupplierCategory(netMap.get(String.valueOf(e.getSupplierCategory())));
            e.setTransactionType(netMap2.get(String.valueOf(e.getTransactionType())));
            e.setSupplierLevel(netMap3.get(String.valueOf(e.getSupplierLevel())));
        });
        return supplierAccessPageListDtos;


    }


    /**
     * 新增供应商准入
     * @param supplierAccessVo
     * @return
     */
    @Override
    public Boolean save(SupplierAccessVo supplierAccessVo) {
        SupplierAccess supplierAccess = new SupplierAccess();
        BeanUtil.copyProperties(supplierAccessVo, supplierAccess);
        supplierAccess.setCreateBy(SecurityUtils.getUsername());
        supplierAccess.setCreateTime(new Date());
        supplierAccess.setProposerBy(SecurityUtils.getUserId());
        supplierAccess.setApplicationDept(SecurityUtils.getDeptId());
        supplierAccess.setApplicationDate(new Date());
        supplierAccess.setStatus("1");
        return save(supplierAccess);
    }


    /**
     * 更新供应商准入
     * @param supplierAccessVo
     * @return
     */
    @Override
    public Boolean updateById(SupplierAccessVo supplierAccessVo) {
        SupplierAccess supplierAccess = new SupplierAccess();
        BeanUtil.copyProperties(supplierAccessVo, supplierAccess);
        supplierAccess.setUpdateBy(SecurityUtils.getUsername());
        supplierAccess.setUpdateTime(new Date());
        supplierAccess.setStatus("1");
        return updateById(supplierAccess);
    }

    /**
     * 获取供应商准入 初始化信息
     * @return
     */
    @Override
    public SupplierAccessInitDto infoInit(){
        SupplierAccessInitDto supplierAccessInitDto=new SupplierAccessInitDto();
        SysDept sysDept = sysDeptService.selectDeptById(SecurityUtils.getDeptId());
        SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
        supplierAccessInitDto.setProposerBy(sysUser.getNickName());
        supplierAccessInitDto.setApplicationDept(sysDept.getDeptName());
        return supplierAccessInitDto;
    }

    /**
     * 提交
     * @param id
     * @return
     */
    @Override
    public Boolean submit(Long id){
        SupplierAccess supplierAccess = new SupplierAccess();
        supplierAccess.setId(id);
        supplierAccess.setStatus("2");
        return updateById(supplierAccess);
    }

    /**
     * 审核
     * @param supplierAccessVo
     * @return
     */
    @Transactional
    @Override
    public Boolean examine(SupplierAccessVo supplierAccessVo){
        SupplierAccess supplierAccess = getById(supplierAccessVo.getId());
        supplierAccess.setId(supplierAccessVo.getId());
        if(supplierAccessVo.getAuditState()==1){
            supplierAccess.setStatus("3");
        }else{
            supplierAccess.setStatus("4");
        }
        supplierAccess.setApproveBy(SecurityUtils.getUserId());
        supplierAccess.setApproveTime(new Date());
        boolean b = updateById(supplierAccess);
        if(b){
            if(("3").equals(supplierAccess.getStatus())){
                SupplierList supplierList=new SupplierList();
                supplierList.setCreateBy(SecurityUtils.getUsername());
                supplierList.setCreateTime(new Date());
                supplierList.setSupplierCode(supplierAccess.getSupplierCode());
                supplierList.setSupplierName(supplierAccess.getSupplierName());
                supplierList.setBillingInfo(supplierAccess.getBillingInfo());
                supplierList.setBusinessLicense(supplierAccess.getBusinessLicense());
                supplierList.setAdmittanceId(supplierAccess.getId());
                supplierList.setSupplierLevel(supplierAccess.getSupplierLevel());
                supplierList.setSupplierCategory(supplierAccess.getSupplierCategory());
                supplierList.setContactPerson(supplierAccess.getContactPerson());
                supplierList.setContactInfo(supplierAccess.getContactInfo());
                supplierList.setSupplierAddress(supplierAccess.getSupplierAddress());
                supplierList.setTransactionType(supplierAccess.getTransactionType());
                supplierListService.save(supplierList);
            }

        }
        return b;
    }

    /**
     * 获取供应商准入详细信息
     * @param id
     * @return
     */
    @Override
    public SupplierAccessDeailsDto getInfoById(Long id){
        return supplierAccessMapper.getInfoById(id);
    }

    /**
     * 供应商信息导出
     * @param supplierAccessVo
     * @return
     */
    @Override
    public List<SupplierAccessPageListDto> export(SupplierAccessVo supplierAccessVo)
    {

        if (supplierAccessVo.getIdStr() != null) {

            List<String> idList = Arrays.asList(supplierAccessVo.getIdStr().split(","));

            supplierAccessVo.setIds(idList);
        }

        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierAccessPageListDto> supplierAccessPageListDtos = supplierAccessMapper.selectByPage(supplierAccessVo);
        supplierAccessPageListDtos.forEach(e->{
            e.setSupplierCategory(netMap.get(String.valueOf(e.getSupplierCategory())));
            e.setTransactionType(netMap2.get(String.valueOf(e.getTransactionType())));
            e.setSupplierLevel(netMap3.get(String.valueOf(e.getSupplierLevel())));
        });
        return supplierAccessPageListDtos;

    }

    /**
     * 供应商准入导入
     * @param coCustomer
     * @return
     */
    @Override
    public String importMouldData(List<SupplierAccessExport> coCustomer)
    {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入供应商准入不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));

        List<SysUser> sysUsers = sysUserMapper.selectUserList(new SysUser());
        Map<String, Long> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserName, SysUser::getUserId));

        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(new SysDept());
        Map<String, Long> deptMap = sysDepts.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId));


        for (SupplierAccessExport supplierExport : coCustomer) {
            SupplierAccess supplierAccess = new SupplierAccess();
            try {

                //供应商编码
                supplierAccess.setSupplierCode(supplierExport.getSupplierCode());
                //供应商名称
                supplierAccess.setSupplierName(supplierExport.getSupplierName());
                //申请人
                supplierAccess.setProposerBy(userMap.get(supplierExport.getProposerBy()));
                //申请部门
                supplierAccess.setApplicationDept(deptMap.get(supplierExport.getApplicationDept()));

                //供应商类别
                supplierAccess.setSupplierCategory(netMap.get(String.valueOf(supplierExport.getSupplierCategory())));
                //供应商交易类型
                supplierAccess.setTransactionType(netMap2.get(String.valueOf(supplierExport.getTransactionType())));
                //供应商等级
                supplierAccess.setSupplierLevel(netMap3.get(String.valueOf(supplierExport.getSupplierLevel())));
                //准入状态
                supplierAccess.setStatus("1");
                supplierAccess.setSupplierAddress(supplierExport.getSupplierAddress());

                //开发原因
                supplierAccess.setDevelopmentReason(supplierExport.getDevelopmentReason());

                //进程/结果
                supplierAccess.setConsequence(supplierExport.getConsequence());

                //紧急程度
                supplierAccess.setUrgencyDegree(supplierExport.getUrgencyDegree());

                //供应商简称
                supplierAccess.setSupplierAbbreviation(supplierExport.getSupplierAbbreviation());
                supplierAccess.setContactPerson(supplierExport.getContactPerson());
                supplierAccess.setContactInfo(supplierExport.getContactInfo());


                boolean save = save(supplierAccess);

                if (!save) {
                    throw new GlobalException("导入失败");
                }

                successNum++;
                successMsg.append(successNum).append("、供应商准入 ").append(supplierAccess.getSupplierName()).append(" 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、供应商准入 " + supplierAccess.getSupplierName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
